package leetcode.N101_N200;

import leetcode.comm.ListNode;

/**
 * @author 歪大哥😁
 * @date 2020-03-27.
 */
public class N160 {

    public static void main(String[] args) {
        ListNode headA = ListNode.generate(2, 3, 4, 5);
        ListNode headB = ListNode.generate(1);
        headB.next = headA;
        ListNode intersectionNode = getIntersectionNode(headA, headB);
    }


    static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode a = headA;
        ListNode b = headB;
        if (a == null || b == null) {
            return null;
        }
        boolean changeA = false;
        boolean changeB = false;
        while (a != b) {
            ListNode aNext = a.next;
            if (aNext != null) {
                a = aNext;
            } else if (!changeA) {
                a = headB;
                changeA = true;
            } else {
                return null;
            }
            ListNode bNext = b.next;
            if (bNext != null) {
                b = bNext;
            } else if (!changeB) {
                b = headA;
                changeB = true;
            } else {
                return null;
            }
        }
        return a;
    }


}
